package com.easy.framework.security.service;

import com.easy.framework.common.constant.Constants;
import com.easy.framework.security.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Set;

/**
 * 自定义权限验证
 *
 */
@Service("perm")
public class PermissionService
{

    /**
     * 验证用户是否具备某权限
     *
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    public boolean hasPermission(String permission)
    {
        if (StringUtils.isEmpty(permission))
        {
            return false;
        }
        Set<String> permissions = SecurityUtils.getPermissions();
        if (CollectionUtils.isEmpty(permissions))
        {
            return false;
        }
        return permissions.contains(Constants.ALL_PERMISSION) || permissions.contains(permission);
    }

    /**
     * 验证用户是否具有以下任意一个权限
     *
     * @param permissions 权限
     * @return 用户是否具有以下任意一个权限
     */
    public boolean hasAnyPermission(String... permissions)
    {
        if (permissions == null || permissions.length == 0)
        {
            return false;
        }
        return Arrays.stream(permissions).anyMatch(s->hasPermission(s));
    }

    /**
     * 判断用户是否拥有某个角色
     *
     * @param roleKey 角色字符串
     * @return 用户是否具备某角色
     */
    public boolean hasRole(String roleKey)
    {
        if (StringUtils.isEmpty(roleKey))
        {
            return false;
        }
        Set<String> roleKeys = SecurityUtils.getRoleKeys();
        if (CollectionUtils.isEmpty(roleKeys)){
            return roleKeys.contains(Constants.SUPER_ADMIN) || roleKeys.contains(roleKey);
        }
        return false;
    }

    /**
     * 验证用户是否具有以下任意一个角色
     *
     * @param roleKeys 角色列表
     * @return 用户是否具有以下任意一个角色
     */
    public boolean hasAnyRole(String... roleKeys)
    {
        if (roleKeys == null || roleKeys.length == 0)
        {
            return false;
        }
        return Arrays.stream(roleKeys).anyMatch(s->hasRole(s));
    }
}
